#!/bin/sh

# This is a quick'n'dirty hack to make the program behave correctly
# under different systems.
# Example:
# when using libc5, (f)trucate's offset argument type is size_t with
# libc5, but it's off_t with libc6 (glibc2).
#
# Uhm... time to learn GNU autoconf :-)

OUTFILE='localdecls.h'

echo '/* This file is automatically generated     *' > $OUTFILE
echo ' * Modify create-localdecls instead of this */' >> $OUTFILE
echo >> $OUTFILE
echo '#ifndef __LOCALDECLS_H_' > $OUTFILE
echo '#define __LOCALDECLS_H_' >> $OUTFILE
echo >> $OUTFILE

###
###
###

echo -n 'Checking truncate argument type... '
if grep -q 'truncate.*size_t' /usr/include/unistd.h ; then
	echo 'size_t'
	echo '#define TRUNCATE_T size_t' >> $OUTFILE
else
	echo 'off_t' # At least, I HOPE it's off_t :-)
	echo '#define TRUNCATE_T off_t' >> $OUTFILE
fi

###
###
###

echo -n 'Checking libc version... '
gcc -Wall -o libctest libctest.c
VERSION=`ldd libctest | grep libc\\.so | awk '{print $1}'`
rm libctest
echo $VERSION
echo "#define LIBC_VERSION \"$VERSION\"" >> $OUTFILE
if test "$VERSION" = 'libc.so.5' ; then
	echo '#define BROKEN_RTLD_NEXT' >> $OUTFILE
	echo '#define LIBC 5' >> $OUTFILE
fi

if test "$VERSION" = 'libc.so.6' ; then
	echo -n 'Checking glibc subversion... '
	tmp="`ldd /bin/sh | grep libc.so 2> /dev/null`"
	LibcPath=`expr "$tmp" : '[^/]*\(/[^ ]*\)'`
	tmp="`strings $LibcPath | grep -i 'c library'`"
	OsLibcMajor=`expr "$tmp" : '.* \([0-9][0-9]*\)'`
	OsLibcMinor=`expr "$tmp" : '.* [0-9][0-9]*\.\([0-9][0-9]*\)'`
	case "$OsLibcMajor" in
	2)
		# 2 is the glibc version
		case "$OsLibcMinor" in
		0)
			echo '#define GLIBC_MINOR 0' >> $OUTFILE
			SUBVERSION='glibc-2.0' ;;
		1)
			echo '#define GLIBC_MINOR 1' >> $OUTFILE
			SUBVERSION='glibc-2.1' ;;
		2)
			echo '#define GLIBC_MINOR 2' >> $OUTFILE
			SUBVERSION='glibc-2.2' ;;
		*)
			echo 'Treated as glibc >= 2.1 (finger crossed)'
			echo '#define GLIBC_MINOR 1' >> $OUTFILE
			SUBVERSION='glibc-2.1' ;;
	        esac
		;;
	esac
fi

echo >> $OUTFILE
echo '#endif' >> $OUTFILE

